﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using eCRAM.Bll;
using eCRAM.Dao;
using eCRAM.Model;
using eCRAM.WebSite.Attributes;
using eCRAM.WebSite.Models;
using eCRAM.WebSite.Tools;
using eCRAM.WebSite.Services;

namespace eCRAM.WebSite.Controllers
{
    [CustomAuthorization(UserRole.ProjectLeader, UserRole.Administrator)]
    public class SearchController : Controller
    {
        //
        // GET: /Search/

        public ActionResult Index()
        {
            return RedirectToAction("SearchCram", new SearchCramModel());
        }

        /// <summary>
        /// Affiche le formulaire de recherche
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult SearchCram(SearchCramModel model)
        {
            if (SessionTools.User.Role == (int)UserRole.Engineer || SessionTools.User.Role == (int)UserRole.SubContractor)
            {
                model.Criterias.UserId = SessionTools.User.Id;
            }

            return View("SearchCram", model);
        }

        /// <summary>
        /// Effectue la recherche
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Search(SearchCramModel model)
        {
            IEnumerable<Guid> activityList =  null;
            if(model.Criterias.ActivityId.HasValue)
            {
                activityList = new List<Guid> {model.Criterias.ActivityId.Value};
            }
            else if (SessionTools.UserIsProjectLeader)
            {
                if (model.Criterias.UserId != SessionTools.User.Id)
                {
                    activityList = ActivityRepository.GetRestrictedActivityList(SessionTools.User.Id).Select(a => a.Id);
                }
            }

            var result = CramRepository.Search(
                model.Criterias.Year, model.Criterias.Month, model.Criterias.UserId,
                model.Criterias.Status, activityList);

            result = result.OrderBy(cram => cram.Year)
                .ThenBy(cram => cram.Month)
                .ThenBy(cram => cram.User.LastName);

            model.Results = result.Select(SearchCramResultModel.FromCram);

            return View("SearchCram", model);
        }

        /// <summary>
        /// Affiche le formulaire de modification d'un cram
        /// </summary>
        /// <param name="idCram"></param>
        /// <returns></returns>
        public ActionResult EditCram(Guid idCram)
        {
            var cram = CramManager.GetCramById(idCram);
            return RedirectToAction("EditCram", "Cram", new { month = cram.Month, year = cram.Year, userId = cram.UserId });
        }

        [HttpPost]
        public ActionResult ValidateCramLine(Guid cramLineId)
        {
            var cramLine = CramLineRepository.GetById(cramLineId);
            if (SessionTools.User.Role == (int)UserRole.ProjectLeader)
            {
                cramLine.Status = (int)CramStatus.Validated;
            }

            if (SessionTools.User.Role == (int)UserRole.Administrator)
            {
                cramLine.Status = (int)CramStatus.Approved;
            }
            cramLine.ValidationDate = DateTime.Now;
            cramLine.Validator = SessionTools.User.Id;
            CramLineRepository.Update(cramLine);

            //CramRepository.Update(cram);

            return RedirectToAction("GetCramsToValid");
        }

        public ActionResult GetCramsToValid()
        {
            var listCrams = CramRepository.GetCramsToValid(SessionTools.User.Id);

            // Construction du model de manière hiérarchique
            var model = listCrams
                .GroupBy(c => new {c.Cram.Month, c.Cram.Year, c.Activity, c.Cram.User})
                .GroupBy(c => new {c.Key.Month, c.Key.Year, c.Key.Activity},
                         c => 
                         new ValidateCramByUserModel
                             {
                                 Id = c.Select(cl => cl.Id).FirstOrDefault(),
                                 User = c.Key.User,
                                 Line = ControllerService.GetCramLineModel(c.Single())
                             })
                .GroupBy(c => new {c.Key.Month, c.Key.Year},
                         c => new ValidateCramByActivityModel {Activity = c.Key.Activity, UsersModel = c})
                .Select(c => new ValidateCramByDateModel {Month = c.Key.Month, Year = c.Key.Year, ActivitiesModel = c});
                
            
            return View("CramsToValid", model);
        }

        
        
        public ActionResult EditByCramLineId(Guid cramLineId)
        {
            var cram = CramRepository.GetByCramLineId(cramLineId);
            return RedirectToAction("EditCram", "Cram", new { month = cram.Month, year = cram.Year, userId = cram.UserId });
        }

    }
}
